package com.bestcem.xm.user.grpc.client;

import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.openplatform.grpc.v1.services.ApiCallCert;
import com.bestcem.xm.openplatform.grpc.v1.services.ApiCallCertSearchResponse;
import com.bestcem.xm.openplatform.grpc.v1.services.BaseOpenplatformServiceGrpc;
import com.bestcem.xm.openplatform.grpc.v1.services.ListApiCallCertRequest;
import com.bestcem.xm.user.grpc.client.convert.BaseOpenplatformGrpcConvert;
import com.bestcem.xm.user.grpc.client.dto.OpenPlatformApiCallCertDTO;
import com.zy.dp.proto.base.v1.Code;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 开放平台grpc服务
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2022/6/9 12:42
 */
@Slf4j
@Service("userBaseOpenplatformGrpcService")
public class BaseOpenplatformGrpcService {

    @GrpcClient(GrpcClientNames.XM)
    private BaseOpenplatformServiceGrpc.BaseOpenplatformServiceBlockingStub stub;

    @Resource
    private BaseOpenplatformGrpcConvert baseOpenplatformGrpcConvert;

    /**
     * 通过公司id获取对应的ApiCallCert
     *
     * @param orgId 公司id
     * @return ApiCallCertDTO
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/6/9 12:56
     */
    public OpenPlatformApiCallCertDTO getApiCallCertByOrgId(String orgId) {
        // 设置请求参数
        ApiCallCert apiCallCert = ApiCallCert.newBuilder().setOrgId(orgId).build();
        ListApiCallCertRequest request = ListApiCallCertRequest.newBuilder().setApiCallCert(apiCallCert).build();
        // 请求
        ApiCallCertSearchResponse response = null;
        try {
            response = stub.listApiCallCert(request);
        } catch (Exception e) {
            log.error("通过公司id获取对应的ApiCallCert。请求失败", e);
        }
        // 返回值处理
        if (response != null && Code.OK_VALUE == response.getStatus().getCodeValue()) {
            List<ApiCallCert> apiCallCertList = response.getApiCallCertListList();
            if (CollectionUtils.isNotEmpty(apiCallCertList)) {
                return baseOpenplatformGrpcConvert.apiCallCertGrpc2Dto(apiCallCertList.get(0));
            }
        } else {
            log.error("通过公司id获取对应的ApiCallCert。请求失败, response:{}", response != null ? response.toString() : null);
        }
        return null;
    }
}
